#include <string.h>
#include <stdlib.h>
#include "catLoad.h"
int loadCategories(char const * filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"r");
	if(!ptr_file){
		return 1;
	}
	int maxlinelen;
	int numlines=getFileInfo(ptr_file,&maxlinelen);
	categorycount=numlines;
	catdata=(struct CategoryVars*) calloc(numlines,sizeof(struct CategoryVars));
	char *buf=(char*) malloc(maxlinelen*sizeof(char));
	for(int i=0;i<numlines;i++){
		fgets(buf,maxlinelen,ptr_file);//load line into buffer;
		sscanf(strtok(buf,"/"), "%d", &catdata[i].id); //get first token from buffer
		strcpy(catdata[i].desc,strtok(NULL,"/"));//subsequent tokens...
	}
	fclose(ptr_file);
	return 0;
}

int writeCategories(char const *filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"w");
	if(!ptr_file){
		return 1;
	}
	for(int i=0;i<categorycount;i++){
		fprintf(ptr_file,"%d/%s\n",catdata[i].id,catdata[i].desc);
	}
	fclose(ptr_file);
	free(catdata);
	return 0;
}

void addCategory(struct CategoryVars n){
	catdata=(struct CategoryVars*) realloc(catdata,++categorycount*sizeof(struct CategoryVars));
	catdata[categorycount-1]=n;
}

void rmCategory(int index){
	for(int i=index;i<categorycount-1;i++){
		catdata[i]=catdata[i+1];
	}
	catdata=(struct CategoryVars*) realloc(catdata,--categorycount*sizeof(struct CategoryVars));
}


void listCategory(){
	for(int i=0; i<categorycount;i++){
		printf("%d. %s", catdata[i].id, catdata[i].desc);
	}
}